package com.gitee.baqkft.code.ui.dlg;

import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gitee.baqkft.code.ui.layout.GBC;

/**
 * TCP/IP调试工具
 * @author chenmingcai
 * @date 2018年7月4日 上午11:37:37 
 *
 */
public class TcpDebugDialog extends JFrame
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * IP地址
	 */
	private JTextField txtIp;
	
	/**
	 * 端口
	 */
	private JTextField txtPort;
	
	/**
	 * 连接按钮
	 */
	private JButton btnConnect;
	
	/**
	 * 连接状态
	 */
	private boolean connected = false;
	
	/**
	 * 连接
	 */
	private SocketChannel channel;
	
	public TcpDebugDialog()
	{
		initUI();
	}

	private void initUI()
	{
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int width = screenSize.width / 2;
		int height = screenSize.height / 2;
		setSize(width, height);
		setLocationByPlatform(true);
		
		setTitle("TCP/IP调试助手");
		
		setLayout(new GridBagLayout());
		GBC gbc = new GBC(0, 0).setWeight(1, 0).setFill(GBC.HORIZONTAL).setInsets(10);
		Panel panel = createConnectionPanel();
		add(panel, gbc);
		
		panel = createSendPanel();
		gbc = new GBC(0, 10).setWeight(1, 1).setFill(GBC.BOTH).setInsets(10);
		add(panel, gbc);
	}
	
	/**
	 * 创建连接设置
	 * @return
	 */
	private Panel createConnectionPanel()
	{
		Panel panel = new Panel();
		panel.setLayout(new GridBagLayout());
		JLabel label = new JLabel("IP");
		GBC gbc = new GBC(0, 0).setWeight(0, 0);
		panel.add(label, gbc);
		
		txtIp = new JTextField("127.0.0.1");
		gbc = new GBC(10, 0).setWeight(0.5, 0).setFill(GBC.HORIZONTAL);
		panel.add(txtIp, gbc);
		
		label = new JLabel("端口");
		gbc = new GBC(20, 0).setWeight(0, 0);
		panel.add(label, gbc);
		
		txtPort = new JTextField("6611");
		gbc = new GBC(30, 0).setWeight(0.2, 0).setFill(GBC.HORIZONTAL);
		panel.add(txtPort, gbc);
		
		btnConnect = new JButton("连接");
		gbc = new GBC(40, 0).setWeight(0, 0);
		panel.add(btnConnect, gbc);
		
		btnConnect.addActionListener(new ActionListener()
		{
			
			@Override
			public void actionPerformed(ActionEvent e)
			{
				if(!connected)
				{
					//执行连接操作
					try
					{
						channel = SocketChannel.open();
						InetSocketAddress remote = new InetSocketAddress(txtIp.getText(), Integer.valueOf(txtPort.getText()));
						channel.connect(remote);
						logger.debug("连接成功");
					}
					catch(IOException ex)
					{
						JOptionPane.showMessageDialog(null, ex.getMessage());
						return;
					}
					connected = true;
					btnConnect.setText("断开");
				}
				else
				{
					//断开连接
					try
					{
						channel.shutdownInput();
						channel.shutdownOutput();
						channel = null;
						logger.debug("连接断开成功");
					}
					catch(IOException ex)
					{
						return;
					}
					connected = false;
					btnConnect.setText("连接");
				}
			}
		});
		
		return panel;
	}
	
	/**
	 * 数据发送配置
	 * @return
	 */
	private Panel createSendPanel()
	{
		Panel panel = new Panel();
		panel.setLayout(new GridBagLayout());
		
		final JTextPane textPane = new JTextPane();
		JScrollPane text = new JScrollPane(textPane);
		GBC gbc = new GBC(0, 0).setWeight(1, 1).setFill(GBC.BOTH);
		panel.add(text, gbc);
		
		Panel options = new Panel();
		gbc = new GBC(0, 10).setWeight(1, 0).setFill(GBC.HORIZONTAL);
		panel.add(options, gbc);
		
		options.setLayout(new GridBagLayout());
		JLabel label = new JLabel("数据类型");
		gbc = new GBC(0, 0).setWeight(0, 0);
		options.add(label, gbc);
		
		final JComboBox<String> box = new JComboBox<String>(new String[]{
			"十六进制", "文本"	
		});
		gbc = new GBC(10, 0).setWeight(0, 0);
		options.add(box, gbc);
		
		JButton btnSend = new JButton("发送");
		gbc = new GBC(20, 0).setWeight(0, 0);
		options.add(btnSend, gbc);
		
		btnSend.addActionListener(new ActionListener()
		{
			
			@Override
			public void actionPerformed(ActionEvent e)
			{
				if(!connected)
				{
					JOptionPane.showMessageDialog(TcpDebugDialog.this, "请先连接服务器");
					return;
				}
				
				ByteBuffer buffer = null;
				String kind = (String)box.getSelectedItem();
				if("十六进制".equals(kind))
				{
					ByteArrayOutputStream bos = hexTextToByte(textPane.getText());
					buffer = ByteBuffer.wrap(bos.toByteArray());
				}
				else
				{
					byte[] data;
					try
					{
						String text = textPane.getText().trim();
						data = text.getBytes("utf-8");
					}
					catch(UnsupportedEncodingException ex)
					{
						logger.error("编码错误");
						data = new byte[0];
					}
					buffer = ByteBuffer.wrap(data);
				}
				try
				{
					do
					{
						channel.write(buffer);
					}while(buffer.hasRemaining());
				}
				catch(Exception ex)
				{
					logger.warn("连接已断开");
					btnConnect.doClick();
				}
			}
		});
		
		return panel;
	}
	
	private ByteArrayOutputStream hexTextToByte(String text)
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		text = text.replaceAll(" ", "");
		char[] array = text.toCharArray();
		for(int i = 0; i + 1 < array.length; i += 2)
		{
			StringBuffer buffer = new StringBuffer();
			buffer.append(array[i]).append(array[i + 1]);
			byte b = (byte)Integer.parseInt(buffer.toString(), 16);
			bos.write(b);
		}
		return bos;
	}
	
	/**
	 * 数据接收线程
	 * @author chenmingcai
	 * @date 2018年7月4日 下午1:33:18 
	 *
	 */
	class DataRecieveThread extends Thread
	{
		
	}
}
